package com.itheima.esdemo;

import com.alibaba.fastjson.JSON;
import com.itheima.esdemo.pojo.User;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
//搜索文档的API
public class EsDemo03 {
    private RestHighLevelClient restHighLevelClient;
    //配置客户端连接地址
    @Before
    public void init(){
        restHighLevelClient = new RestHighLevelClient(
                RestClient.builder(
                        // 要连接的es地址
                        new HttpHost("192.168.200.150",9200,"http")
                        ,new HttpHost("192.168.200.151",9200,"http")   // 如果是集群的话可以写多个
                        ,new HttpHost("192.168.200.152",9200,"http")
                        ,new HttpHost("192.168.200.153",9200,"http")
                )
        );
    }



    //分词查询：搜索note字段中包含 唱歌javaee的文档
    @Test
    public void matchDocument() throws IOException {

        SearchSourceBuilder builder = new SearchSourceBuilder();
        //1.构建一个match条件
        builder.query(QueryBuilders.matchQuery("note","唱歌javaee"));
        //2.打印结果
        printDocumentResult(builder);
    }

    //词条查询：搜索性别为女的所有同学
    @Test
    public void termDocument() throws IOException {
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.termQuery("gender", 0));
        printDocumentResult(builder);
    }

    //范围查询 ：搜索年龄在22到28之间的所有同学
    @Test
    public void rangeDocument() throws IOException {
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.rangeQuery("age").gte(22).lte(28));
        printDocumentResult(builder);
    }

    /**布尔查询
     * 查询 文档note字段中  包含 同学
     * 并且 性别为 1
     * 并且 年龄小于 26岁
     */
    @Test
    public void boolDocument() throws IOException {
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("note","同学"))
                .filter(QueryBuilders.termQuery("gender","1"))
                .filter(QueryBuilders.rangeQuery("age").lte(26)));
        printDocumentResult(builder);

    }

    //查询全部文档数据
    @Test
    public void matchAllDocument() throws IOException {
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.matchAllQuery());
        printDocumentResult(builder);
    }


    /**
     * 将通用的代码封装
     * 外部只需要构建builder条件 传入即可
     * @param builder
     * @throws IOException
     */
    public void printDocumentResult(SearchSourceBuilder builder) throws IOException {
        // 1. 创建搜索请求对象   SearchRequest
        SearchRequest request = new SearchRequest("user");
        request.source(builder);
        // 2. 客户端执行搜索请求  client.search
        SearchResponse searchResponse = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        // 3. 解析响应结果   SearchResponse
        // response.getHits
        SearchHits hits = searchResponse.getHits(); // 查询结果
        // .getToTalHits().value 查询结果总数量
        System.out.println("查询结果数量:" + hits.getTotalHits().value);
        // .getHits  得到文档列表
        SearchHit[] docList = hits.getHits();
        //      遍历文档列表
        for (SearchHit searchHit : docList) {
            //          .getSource 获取文档内容
            String userJson = searchHit.getSourceAsString();
            User user = JSON.parseObject(userJson,User.class);
            System.out.println(user);
        }
        //          .getHighligher 获取高亮处理结果
        // response.getAggregations 获取聚合结果
    }


    //关闭客户端
    @After
    public void close() throws IOException {
        restHighLevelClient.close();
    }
}
